package run.iget.framework.event;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class EventPublishUtils implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher APPLICATION_EVENT_PUBLISHER = null;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        APPLICATION_EVENT_PUBLISHER = applicationEventPublisher;
    }

    /**
     * 发送事件
     * @param event
     */
    public static void publish(AppEvent event) {
        if (log.isDebugEnabled()) {
            log.debug("发布事件消息：{}", JSON.toJSONString(event));
        }
        APPLICATION_EVENT_PUBLISHER.publishEvent(event);
    }

    /**
     * 发送事件
     * @param source 事件消息对象
     */
    public static void publish(Object source) {
        AppEvent appEvent = null;
        if (source instanceof AppEvent) {
            appEvent = (AppEvent) source;
        } else {
            appEvent = AppEvent.of(source);
        }
        publish(appEvent);
    }

}
